// pages/shop/cart/cart.js
var that,
  api = new(require('../../utils/api.js')),
  app = getApp(),
  headimg = api.getimgurl(),
  util = new(require('../../utils/util.js'));
Page({

  /**
   * 页面的初始数据
   */
  data: {
    headimg,
    // nolist: !0,
    show_totalcount: 0,
    total: 0,
    getall: 0,
    getoneall:0,
    switcharr: [],
    list: [],
    inputvalue: '',
    totalnumber: 0,
    noaddress: !0,
    sendtype: 1,
    start: 0,
    pagesize: 20,
    // carlist:[],
    topimage: '',
    imglist: [],
    price:0,
    isload:!1,
    isedit:!1,
    totalscore:0,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    that = this;
    let origuserinfo = wx.getStorageSync('userinfo'), {type}=app.logininfo.user
    that.setData({origuserinfo,usertype:type})
    that.getdata()
  },
  getdata(){
    api.getcargoodslist( res => {
      if (res.data.issuccess == 1) {
        let list =[],carlist = res.data.list
        wx.setStorageSync('carlist', carlist) 
        if(res.data.list.length>0){
          res.data.list.forEach((x, i) => {
            x.check=0;
            x['newprice']=(x.promotionprice/100).toFixed(2)
            // x.newprom=(x.promotionprice/100).toFixed(2)
            list.push(x)
          })
        }
          that.setData({ list,isload:!0 })
      }
     
    })
  },
  toindex(){
    wx.switchTab({
      url: '../shoppingMall/shoppingMall',
    })
  },
  tomain() {
    wx.switchTab({
      url: '../classification/classification',
    })
  },

  getlist(list) {
    var show_totalcount = '',
      totalcount = 0, totalnumber=0,{switcharr} = this.data;
    if (list.length > 0) {
      list.map((x, i) => {
        list[i]['check'] = switcharr.indexOf(i)>-1?1:0
        list[i]['newprice']=(x.promotionprice/100).toFixed(2)
        totalcount += Number(list[i]['promotionprice']) * x.goodscount
        show_totalcount = (totalcount / 100).toFixed(2)
      })
      // console.log("isbuy", isbuy); 
      that.setData({
        nolist: !1,
        list: list,
        totalcount,
        show_totalcount,
        getall: (switcharr.length==list.length&&switcharr.length!=0)?1:0
      })
    } else {
      this.setData({
        list: [],
        nolist: !0
      })
    }
    this.counttotal();
  },





  counttap(e) {
    //totalnumber  共计数
    //show_totalcount 总计金额
    let { code, item,index } = e.currentTarget.dataset
    if( code == 0 &&Number(item.paynum) == 1){
      console.log(item,'itemitemitem');
      let {id,goodsid} = item
      console.log(id,'iddididiid');
      api.delcart({ids:goodsid}, res => {
        if (res.data.issuccess == 1) {
          let carlist = wx.getStorageSync("carlist");
          carlist.splice(index, 1)
          wx.setStorageSync("carlist", carlist);
          that.getlist(res.data.list)
        }
      });
    }else{
      api.setCartcount({ id: item.id, count: code == 0 ? Number(item.paynum) - 1 : Number(item.paynum) + 1},res=>{
        if(res.data.issuccess==1){
          //处理list
          that.getlist(res.data.list)
        }
      })
    }
  },
  toaddress() {
    wx.navigateTo({
      url: '../addressadd/addressadd',
    })
  },

  todetail(e) {
    let id = e.currentTarget.dataset.idx;

    wx.navigateTo({
      url: '../detail/detail?id=' + id,
    })
  },
  getchecklist(cart) {
    let {
      isscore
    } = this.data, checklist = [], total = 0, cartids = [];
    cart.forEach((x, i) => {
      if (x.check == 1) {
        cartids.push(x.id)
        checklist.push(x)
        total += x.goodscount * x.price
      }
    })
    if (!isscore) {
      // that.getcoupon(total);
    }
    that.setData({
      checklist,
      total,
      cartids,
      origintotal: total
    })

  },
  //删除商品
  delcarlist(e) {
    let { id,index, check} = e.currentTarget.dataset, {list, start, pagesize} = this.data, openid = wx.getStorageSync("openid");
    console.log('check',check)
    wx.showModal({
      title: '删除商品',
      content: '确认删除吗？',
      success: function(res) {
        if (res.confirm) {
          api.delcart({ids:id}, res => {
            if (res.data.issuccess == 1) {
              let carlist=wx.getStorageSync("carlist");
              carlist.splice(index,1)
              wx.setStorageSync("carlist", carlist);
              if(check==1){
                let {switcharr} = that.data;
                switcharr.splice(index,1)
                that.setData({ switcharr})
              }
              that.getlist(res.data.list)
              that.getonelist(res.data.onelist)
            }
          });
        }
      },
    })
  },
  toconfirm() {
    let userinfo = wx.getStorageSync('userinfo'), { origuserinfo,totalnumber}=this.data
    if (totalnumber<=0){
      wx.showModal({
        title: '提示',
        content: '还没有选中任何商品哦~',
        showCancel: !1
      })
      return;
    }
    if (!origuserinfo) {
      wx.showModal({
        title: '提示',
        content: '请先登录，再提交订单',
        showCancel: false,
        success: function(res) {
          if (res.confirm) {
            wx.redirectTo({
              url: '../empower/empower',
            })
          }
        }
      })
      return;
    }
    var {
      switcharr, list,address
    } = this.data, goodssn = [], goodscount=[],cartids = [];
    switcharr.forEach(x=>{
      list.forEach(y=>{
        if(x=y.goodsid){
          // goodssn.push(y['goodsnum'])
          goodscount.push(y['paynum'])
          cartids.push(y.goodsid)
        }
      })
      
    })
    that.setData({addorderdata:{ goodssn: goodssn.join(','), goodscount: goodscount.join(','), cartids: cartids.join(',')}},()=>{
      wx.navigateTo({
              url: '../confirm/confirm?total='+that.data.total,
            })
    })
  },
  getall() {
    var {getall, list} = this.data,issel=!1;
    getall = getall == 1 ? 0 : 1;
    list.map((x, i) => {
      list[i]['check'] = getall
    })
    this.setData({
      list,
      getall
    }, () => {
      this.counttotal()
    });
  },

  switchtap(e) {
    let {
      check,
      index
    } = e.currentTarget.dataset, {
      list,
      selects,
      totalcount,
      switcharr
    } = this.data;
    console.log(check, 'check')
    list[index].check = check == 0 ? 1 : 0
    this.counttotal();
    this.setData({
      list,
      getall: 0
    })
  },
  

  //计算总价
  counttotal() {
    var { list } = this.data, total = 0, switcharr = [], totalnumber = 0, show_totalcount = 0;
    list.forEach((x, i) => {
      if (x.check == 1) {
        switcharr.push(x.goodsid)
        total += Number(x.promotionprice) * Number(x.paynum);
        totalnumber += Number(x.goodscount)
      }
    })
    show_totalcount = (total / 100).toFixed(2);
    this.setData({
      total,
      switcharr,
      totalnumber,
      show_totalcount
    })
  },

  // 编辑
  edit(){
    let {isedit,list}=that.data
    list.forEach(x=>{
      x['check']=0
    })
    that.setData({isedit:!isedit,list,getall:0,switcharr:[]})
  },
  // 删除
  delcart(){
    let {switcharr}=that.data
    if(switcharr.length==0){
        wx.showToast({
          title: '您还没选择需要删除的商品',
          icon: 'none'
        })
        return;
    }else{
      let ids=switcharr.toString()
      wx.showModal({
        title: '删除商品',
        content: '确认删除吗？',
        success: function(res) {
          if (res.confirm) {
            api.delcart({ids}, res => {
              if (res.data.issuccess == 1) {
                let carlist=wx.getStorageSync("carlist");
                // console.log(carlist,'carlistcarlistcarlistcarlistcarlist');
                switcharr.forEach((x,i)=>{
                  carlist.forEach((y,j)=>{
                    if(y.id==x){
                      carlist.splice(j,1)
                    }
                  })
                })
                wx.setStorageSync("carlist", carlist);
                that.getlist(res.data.list)
                that.setData({switcharr:[],isedit:!1})
              }
            });
          }
        },
      })
    }
  },
  getuserinfo(e){
    console.log(e,'eeee');
    that.toconfirm()
    let {origuserinfo}=that.data
    if(!origuserinfo){
      if (e.detail.userInfo){
        let {userInfo} = e.detail;
        api.updateUser({avatar:userInfo.avatarUrl,name:userInfo.nickName},res=>{
          if(res.data.issuccess==1){
            that.setData({origuserinfo:e.detail.userInfo},()=>{
              wx.setStorageSync('userinfo', userInfo);
              that.toconfirm()
            })
          }else{
            wx.showModal({
              title: '提示',
              content:'登录失败，请重新登录',
              success:function(res){
                if(res.confirm){
                  that.getuserinfo(e)
                }
              },
            })
          }
        })
      }
    }
    this.getscore(res=>{
      wx.setStorageSync('userinfo', userInfo);
    });
    
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  getpricebycodes(cart) {
    if (cart.length < 1) {
      this.setData({
        list: [],
        // nolist: !0
      });
      this.counttotal();
      return;
    }
    var codes = [];
    cart.forEach((x, i) => {
      codes.push(x.code);
    })
    codes = codes.join(",");

  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    let {isload}=that.data
    that.setData({totalnumber:0,show_totalcount:0,getoneall:0,getall:0},()=>{
      if(isload){
        that.getdata()
      }
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  }
})